package com.ljx.demo.service.impl;

import com.ljx.demo.domain.vo.req.LoginForm;
import com.ljx.demo.domain.vo.resp.ApiResult;
import com.ljx.demo.security.core.LoginUser;
import com.ljx.demo.security.core.UserHolder;
import com.ljx.demo.service.AuthService;
import com.ljx.demo.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

/**
 * @Author: LiJunXi
 * @Description:
 * @Date: 2024-06-17  09:43
 */
@Service
public class AuthServiceIImpl implements AuthService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public String login(LoginForm loginForm) {
        // 若有其他检验项也需要检查
        Authentication authentication = null;
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginForm.getUsername(), loginForm.getPassword());
            UserHolder.setContext(authenticationToken);
            // 这里会调用 UserDetailService 类的 loadUserByUsername 方法
            authentication = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            UserHolder.clearContext();
        }
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();

        return JwtUtil.createToken(loginUser.getUsername());
    }
}
